package com.tengju.payment.infrastructure.shared;

import java.io.*;

/**
 * @author: 李大仙
 * @date: 2021/7/2 4:21 下午
 */
public class FileUtil {

    /**
     * 将str转换为inputStream
     *
     * @param str
     * @return
     */
    public static InputStream str2InputStream(String str) {
        ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());
        return is;
    }

    /**
     * 将inputStream转化为file
     *
     * @param is
     * @param file 要输出的文件目录
     */
    public static void inputStream2File(InputStream is, File file) throws IOException {
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int len = 0;
            byte[] buffer = new byte[8192];

            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } finally {
            if (os != null) {
                os.close();
            }
            is.close();
        }
    }

    public static void string2File(String str, File file) throws IOException {
        ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes());
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int len;
            byte[] buffer = new byte[8192];

            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } finally {
            if (os != null) {
                os.close();
            }
            is.close();
        }
    }
}
